package com.example.chessbattleplatform.web.chess_rooms.websocket;

import com.example.chessbattleplatform.Interceptor.WebSocketSetUserConfigurator;
import com.example.chessbattleplatform.Pojo.WebSocketSessionIdAndUserId;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.Vo.RoomsDataVo;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.websocket.QueryInformationAboutUserCurrentRoom;
import com.example.chessbattleplatform.web.chess_rooms.service.impl.RoomsServiceInterface;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/roomsMember", configurator = WebSocketSetUserConfigurator.class)
public class RoomsMemberWebSocketServer {
    // 存储所有的session
    public static final QueryInformationAboutUserCurrentRoom webSocketSessionSendMessage = new QueryInformationAboutUserCurrentRoom();

    // 查询 service
    private static RoomsServiceInterface roomsService;

    //发送 列表 房间 数据
    public static void sendQueriesMessage(Session session) {
        webSocketSessionSendMessage.sendQueriesMessage(session, roomsService);
    }

    // 群发 列表 房间 数据
    public static void sendQueriesMessages() {
        webSocketSessionSendMessage.sendQueriesMessages(roomsService);
    }

    // 静态导入
    @Autowired
    public void setRoomsService(RoomsServiceInterface roomsService) {
        // 静态导入 房间服务
        RoomsMemberWebSocketServer.roomsService = roomsService;
    }

    // 链接建立
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        // 获取token 并 校验
        Long user_id = Long.valueOf((String) config.getUserProperties().get("user_Id"));

        try {
            //获取 用户房间数据
            RoomsDataVo room = roomsService.getRoom(user_id);
            webSocketSessionSendMessage.sendSuccessMessage(room, session);
        } catch (Exception e) {
            log.error("Session：{} 链接关闭,删除", session.getId());
            throw new RuntimeException(e);
        }

        // 存储 session
        webSocketSessionSendMessage.addSessionMap(session, WebSocketSessionIdAndUserId.builder()
                .userId(user_id)
                .session(session).build());
    }

    // 链接关闭
    @OnClose
    public void onClose(Session session) {
        WebSocketSessionIdAndUserId remove = webSocketSessionSendMessage.deleteSessionMap(session);
//        log.info("Session：{} 链接关闭,删除{}", session.getId(), remove);
    }

    // 接收消息
    @OnMessage
    public void onMessage(Session session, String message) {

    }

    // 错误
    @OnError
    public void onError(Session session, Throwable throwable) {

    }
}
